package com.example.partyfee.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.example.partyfee.dto.SalaryExcelDTO;
import com.example.partyfee.entity.Salary;
import com.example.partyfee.service.SalaryService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 工资Excel导入监听器
 */
@RequiredArgsConstructor
public class SalaryImportListener implements ReadListener<SalaryExcelDTO> {

    private final SalaryService salaryService;
    private final String salaryMonth;
    private final String batchNo;
    private final List<String> errorMessages = new ArrayList<>();
    private final List<Salary> cachedDataList = new ArrayList<>();
    private static final int BATCH_COUNT = 100;

    @Override
    public void invoke(SalaryExcelDTO data, AnalysisContext context) {
        Salary salary = new Salary();
        BeanUtils.copyProperties(data, salary);
        salary.setSalaryMonth(salaryMonth);
        salary.setBatchNo(batchNo);
        salary.setCreateTime(LocalDateTime.now());
        cachedDataList.add(salary);
        
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        cachedDataList.clear();
    }

    private void saveData() {
        if (!cachedDataList.isEmpty()) {
            try {
                salaryService.batchSaveSalaries(cachedDataList);
            } catch (Exception e) {
                errorMessages.add("批量保存数据失败：" + e.getMessage());
            }
        }
    }

    public List<String> getErrorMessages() {
        return errorMessages;
    }
} 